package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"

	"manager/auth"
)

type feedback struct {
	iFeedback store.IFeedback
}

var Feedback = &feedback{
	iFeedback: postgres.Feedback,
}

func (a *feedback) init() func() {
	return func() {}
}

func (a *feedback) onEvent(*event.Data) {}

// Create 创建
func (a *feedback) Create(ctx context.Context, in *model.FeedbackCreateRequest) error {
	var (
		err error
	)

	// 获取用户Id
	in.UserId, _ = auth.ContextUserID(ctx)

	// 构建创建现场数据
	c := buildFeedback(in)
	_, err = a.iFeedback.Create(ctx, c)
	return err
}

// Update 更新
func (a *feedback) Update(ctx context.Context, in *model.FeedbackUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.UserName != nil {
		dict["user_name"] = in.UserName
	}

	if in.Phone != nil {
		dict["phone"] = in.Phone
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.Details != nil {
		dict["details"] = in.Details
	}

	if in.Images != nil {
		dict["images"] = in.Images
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iFeedback.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *feedback) Delete(ctx context.Context, in *model.FeedbackDeleteRequest) error {
	return a.iFeedback.Delete(ctx, in.Id)
}

// List 列表查询
func (a *feedback) List(ctx context.Context, in *model.FeedbackListRequest) (*model.FeedbackListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Feedback
		out   = &model.FeedbackListResponse{}
	)

	if total, list, err = a.iFeedback.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.FeedbacksEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *feedback) Find(ctx context.Context, in *model.FeedbackInfoRequest) (*model.FeedbackInfo, error) {
	var (
		err  error
		data *entity.Feedback
		out  = &model.FeedbackInfo{}
	)

	if data, err = a.iFeedback.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.FeedbackEntityToDto(data)
	return out, nil
}

// buildFeedback 构建创建数据现场
func buildFeedback(in *model.FeedbackCreateRequest) *entity.Feedback {
	// todo: check the entity is required
	return &entity.Feedback{

		UserId: in.UserId,

		UserName: in.UserName,

		Phone: in.Phone,

		Type: in.Type,

		Details: in.Details,

		Images: in.Images,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
